<?php
include_once '../utils/constants.php';
include_once '../utils/debug.php';
include_once 'game.php';
include_once '../utils/utils.php';

class Games {

	/**
	 * Array with Game objects
	 */
	var $games = array();

	public function Games() {
		if (DEBUG) enex("Games::Games()");
	}

	/**
	 * Reads all games from local disk file
	 */
	public function buildFromFile($filename) {
		if (DEBUG) enter("Games::buildFromFile($filename)");
		$gamesStringArray = getGamesStringArray($filename);
		foreach ($gamesStringArray as $gameString) {
			if (DEBUG) debug("Games::buildFromFile, game string: $gameString");
			array_push($this->games, new Game($gameString));
		}
		if (DEBUG) {
			debug("Games::buildFromFile(), games=");
			var_dump($this->games);
		}
		if (DEBUG) ex("Games::buildFromFile()");
		return $this;
	}

	public function getGamesStringArray($filename) {
		if (DEBUG) enter("Games::getGamesStringArray($filename)");
		$content = file_get_contents($filename);
		$gamesStringArray = split("\n", $content);
		if (DEBUG) {
			debug("Games::getGamesStringArray(), gamesStringArray=");
			var_dump($gamesStringArray);
			ex("Games::getGamesStringArray()");
		}
		return $gamesStringArray;
	}

	/**
	 * read games from local disk file with specified ids
	 */
	public function buildFromFilePartially($filename, $idArray) {
		if (DEBUG) enter("Games::buildFromFilePartially($filename, $idArray)");
		$gamesStringArray = $this->getGamesStringArray($filename);
		foreach ($gamesStringArray as $gameString) {
			list($id) = split(" ", $gameString);
			$res = array_search($id, $idArray, TRUE);
			if($res !== false) {
				$gam = new Game();
				array_push($this->games, $gam->buildFromString(($gameString)));
			}
		}
		if (DEBUG) {
			debug("Games::buildFromFilePartially($filename, $idArray), games=");
			var_dump($this->games);
			ex("Games::buildFromFilePartially($filename, $idArray)");
		}
		return $this;
	}

	public function generateId() {
		if (DEBUG) enex("Games::generateId()");
		return getMaxId(GAMES) + 1;
	}
}

?>